//
//  CategoryiewController.swift
//  Memorandum
//
//  Created by CurryZhang on 2019/9/25.
//  Copyright © 2019 CurryZhang. All rights reserved.
//

import UIKit

class CategoryiewController: UITableViewController, CategoryDetailViewControllerDelegate, UINavigationControllerDelegate {
    func categoryDetailViewController(_ controller: CategoryDetailViewController, didFinishAdding category: TodoCategory) {
        let newIndex = categories.count
        categories.append(category)
        let indexPath = IndexPath(row: newIndex, section: 0)
        let indexPaths = [indexPath]
        tableView.insertRows(at: indexPaths, with: .automatic)
        dismiss(animated: true, completion: nil)
    }
    
    func categoryDetailViewController(_ controller: CategoryDetailViewController, didFinishEditing category: TodoCategory) {
        if let index = categories.firstIndex(of: category){
            categories[index].name = category.name
            
            let indexPath = IndexPath(row: index, section: 0)
            let cell = tableView.cellForRow(at: indexPath)
            cell?.textLabel?.text = category.name
        }
        
        dismiss(animated: true, completion: nil)
    }
    var categories: [TodoCategory]
    
    required init?(coder aDecoder: NSCoder) {
        categories = [TodoCategory]()
        super.init(coder: aDecoder)
        
        loadCategories()
    }

    override func viewDidLoad() {
        super.viewDidLoad()


    }
    
    func documentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
        
    }
    func dataFilePath() -> URL {
        return documentsDirectory().appendingPathComponent("Todolists.plist")
    }
    func savaCategories() {
        let data = NSMutableData()
        let archiver = NSKeyedArchiver(forWritingWith: data)
        archiver.encode(categories, forKey: "TodoCategories")
        archiver.finishEncoding()
        data.write(to: dataFilePath(), atomically: true)
    }

    func loadCategories() {
        let path = dataFilePath()
        if let data = try? Data(contentsOf: path){
            let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
            categories =  unarchiver.decodeObject(forKey: "TodoCategories") as! [TodoCategory]
            unarchiver.finishDecoding()
        }
    }


    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return categories.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellId = "Cell"
        var cell =  tableView.dequeueReusableCell(withIdentifier: cellId)
        if cell == nil {
            cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)
        }


       let category = categories[indexPath.row]
        cell?.textLabel?.text = category.name
        let num = category.countItems()
        if category.items.count == 0 {
            cell?.detailTextLabel?.text = "还没有创建备忘录"
        }else if num == 0{
            cell?.detailTextLabel?.text = "备忘录都已完成"
            
        }else {
            cell?.detailTextLabel?.text = "还有\(num)个备忘录未完成"
        }
        cell?.imageView?.image = UIImage(named: category.iconImage)
        
        
        cell?.accessoryType = .detailDisclosureButton
        
        return cell!
    }
    
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        categories.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .automatic)
    }
    
    override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
        let category = categories[indexPath.row]
        let nav = storyboard!.instantiateViewController(withIdentifier: "CategoryNaviController") as! UINavigationController
        let dest = nav.topViewController as! CategoryDetailViewController
        dest.delegate = self
        dest.categoryToEdit = category
        
        present(nav, animated: true, completion: nil)
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        UserDefaults.standard.set(indexPath.row, forKey: "CategoryIndex")
        
        let category = categories[indexPath.row]
        performSegue(withIdentifier: "ShowTodoItems", sender: category)
    }
    
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "ShowTodoItems" {
            let category = sender as! TodoCategory
            let todoVC = segue.destination as! TodoViewController
            todoVC.category = category
        } else if segue.identifier == "AddCategory" {
            let navController = segue.destination as! UINavigationController
            let controller = navController.topViewController as! CategoryDetailViewController
            controller.delegate = self
        }
    }
    
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        if viewController === self {
            UserDefaults.standard.set(-1, forKey: "CategoryIndex")
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        navigationController?.delegate = self
        
        let index = UserDefaults.standard.integer(forKey: "CategoryIndex")
        if index != -1{
//            let category = categories[index]
//            performSegue(withIdentifier: "ShowTodoItems", sender: category)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        tableView.reloadData()
    }
}
